package com.thermofisher.dsc.amanda.common.excel.scheduled;

import com.hierynomus.msdtyp.AccessMask;
import com.hierynomus.msfscc.FileAttributes;
import com.hierynomus.mssmb2.SMB2CreateDisposition;
import com.hierynomus.mssmb2.SMB2CreateOptions;
import com.hierynomus.mssmb2.SMB2ShareAccess;
import com.hierynomus.smbj.SMBClient;
import com.hierynomus.smbj.auth.AuthenticationContext;
import com.hierynomus.smbj.connection.Connection;
import com.hierynomus.smbj.session.Session;
import com.hierynomus.smbj.share.DiskShare;
import com.hierynomus.smbj.share.File;
import com.thermofisher.dsc.amanda.config.SmbConfig;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashSet;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author wenjie.yang on 4/10/2019.
 */
@Service
public class ShareFileService {
  @Autowired
  private SmbConfig smbConfig;


  public  InputStream smbGet(String filename) throws IOException {
    SMBClient client = new SMBClient();
    Connection connection = client.connect(smbConfig.getHostname());
    AuthenticationContext ac = new AuthenticationContext(smbConfig.getUsername(), smbConfig.getPassword().toCharArray(), "");
    Session session = connection.authenticate(ac);
    File f = null;
    DiskShare share = null;
    // Connect to Share
    try  {
      share= (DiskShare) session.connectShare(smbConfig.getShareDir());
        f = share.openFile(filename,
            new HashSet(Arrays.asList(AccessMask.GENERIC_ALL)),
            new HashSet(Arrays.asList(FileAttributes.FILE_ATTRIBUTE_NORMAL)),
            SMB2ShareAccess.ALL,
            SMB2CreateDisposition.FILE_OPEN,
            new HashSet(Arrays.asList(SMB2CreateOptions.FILE_DIRECTORY_FILE))
        );
      return f.getInputStream();
    }catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }


  public static InputStream fun() throws Exception {
    String remotePhotoUrl = "smb://CNSHO-JSHPZM2/Shared/E1Customer.xlsx";
    SmbFile remoteFile = new SmbFile(remotePhotoUrl);
    remoteFile.connect(); //尝试连接
    //创建文件流
    InputStream inputStream = new BufferedInputStream(new SmbFileInputStream(remoteFile));

    return inputStream;
  }

  public static void main(String[] args) throws Exception{
    InputStream fun = fun();
    System.out.println(fun);
  }

}
